<template>
  <div style="padding:15px;">
    <el-form ref="formInline" :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item prop="loginName">
        <el-input v-model="formInline.loginName" placeholder="账户名" class="el-input--mini" prefix-icon="el-icon-search" maxlength="20" />
      </el-form-item>
      <el-form-item prop="userName">
        <el-input v-model="formInline.userName" placeholder="昵称" class="el-input--mini" prefix-icon="el-icon-search" maxlength="20" />
      </el-form-item>
      <el-form-item prop="phone">
        <el-input v-model="formInline.phone" placeholder="手机号" class="el-input--mini" prefix-icon="el-icon-search" oninput="value=value.replace(/^\.+|[^\d.]/g,'')" maxlength="11" />
      </el-form-item>
      <el-form-item prop="sex">
        <el-select v-model="formInline.sex" clearable placeholder="性别" class="el-input--mini">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="userStatus">
        <el-select v-model="formInline.userStatus" clearable placeholder="账户状态" class="el-input--mini">
          <el-option
            v-for="item in status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" class="el-button--mini" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-delete" class="el-button--mini" @click="onReset('formInline')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-user" class="el-button--mini" @click="onAddUser('formInline')">添加用户</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="fullscreenLoading"
      :data="tableData"
      border
      text-align="center"
      align="center"
      style="padding-top:20px;"
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
      stripe
      :row-style="{height:'10px'}"
      :cell-style="{padding:'0px'}"
    >
      <el-table-column prop="id" label="ID" width="70px" sortable />
      <el-table-column prop="loginName" label="账户" width="150px" />
      <el-table-column prop="userName" label="昵称" width="150px" />
      <el-table-column prop="phone" label="手机号" width="150px" />
      <el-table-column prop="sex" label="性别" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.sex | sexTagFilter">
            {{ scope.row.sex | sexfilters }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userStatus" label="账户状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.userStatus | statusTagFilter">
            {{ scope.row.userStatus | userStatusfilters }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180px" sortable>
        <template slot-scope="scope">
          <p>{{ scope.row.createdTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作">
        <template slot-scope="scope">
          <div>
            <el-button type="primary" size="small" icon="el-icon-edit" @click="queryUserInfo(scope.row.id,'editUserFormInline')">编辑</el-button>
            <el-button :type="scope.row.userStatus | statusTagFilter" size="small" icon="el-icon-close" @click="forbiddenUser(scope.row,'editUserFormInline')">{{ scope.row.userStatus ==1? '禁用':'启用' }}</el-button>
            <el-button type="danger" size="small" icon="el-icon-thumb" @click="resetUserPwd(scope.row,'editUserFormInline')">重置密码</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-divider />
    <div class="block">
      <el-pagination
        :total="page.totalCount"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      element-loading-text="拼命加载中"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form
        ref="editUserFormInline"
        :model="editUserFormInline"
        :rules="rules"
      >
        <el-form-item label="登录账户" :label-width="formLabelWidth" prop="loginName">
          <el-input v-model="editUserFormInline.loginName" autocomplete="off" maxlength="21" :disabled="!isAdd" class="el-input--medium" />
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="userName">
          <el-input v-model="editUserFormInline.userName" autocomplete="off" maxlength="21" class="el-input--medium" />
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="editUserFormInline.phone" autocomplete="off" maxlength="11" class="el-input--medium" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
          <el-select v-model="editUserFormInline.sex" name="editSex" placeholder="性别" clearable class="el-input--medium">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态" :label-width="formLabelWidth" prop="userStatus">
          <el-select v-model="editUserFormInline.userStatus" name="editUserStatus" placeholder="账户状态" clearable class="el-input--medium">
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择角色" :label-width="formLabelWidth" prop="roleList">
          <el-transfer
            v-model="editUserFormInline.roleList"
            class="el-input--medium"
            :titles="['请选择角色', '已选角色']"
            :data="transferData"
            filterable
            @change="handleChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--medium" @click="cancelChange('editUserFormInline')">取 消</el-button>
        <el-button class="el-button--medium" type="primary" @click="updateUserInfo('editUserFormInline')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserList, getUserByUserId, updateAuthUserInfoAndRole, resetUserPwd, queryAuthRoleAllByStatus, admin_register } from '@/api/system/user'

export default {
  name: 'Dashboard',
  filters: {
    timefilters(val) {
      if (val == null || val === '') {
        return '暂无时间'
      } else {
        const d = new Date(val) // val 为表格内取到的后台时间
        const month =
          d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
        const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
        const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
        const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
        const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
        return times
      }
    },
    sexfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '男'
        } else {
          return '女'
        }
      }
    },
    sexTagFilter(val) {
      const statusMap = {
        '1': 'success',
        '2': 'warning'
      }
      return statusMap[val]
    },
    userStatusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '正常'
        }
        if (val === 2) {
          return '锁定'
        }
        if (val === 3) {
          return '删除'
        }
        if (val === 4) {
          return '非法'
        }
      }
    },
    statusTagFilter(val) {
      const statusMap = {
        '1': 'success',
        '2': 'info',
        '3': 'danger',
        '4': 'danger'
      }
      return statusMap[val]
    }
  },
  data() {
    return {
      fullscreenLoading: true,
      options: [{
        value: 1,
        label: '男'
      }, {
        value: 2,
        label: '女'
      }],
      status: [{
        value: 1,
        label: '正常'
      }, {
        value: 2,
        label: '锁定'
      }, {
        value: 3,
        label: '删除'
      }, {
        value: 4,
        label: '非法'
      }],
      formInline: {
        loginName: '',
        userName: '',
        phone: '',
        sex: '',
        userStatus: ''
      },
      dialogTitle: '',
      isAdd: true,
      editUserFormInline: {
        userId: '',
        loginName: '',
        userName: '',
        phone: '',
        sex: '',
        userStatus: '',
        roleList: []

      },
      tableData: [],
      page: {
        'rowCount': 10,
        'currentPage': 1,
        'pageSize': 10,
        'pageCount': 2,
        'totalCount': 0,
        'orderBy': null,
        'outofBounds': false,
        'limitStart': 0
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '80px',
      editUserSex: '',
      transferData: [],
      rules: {
        loginName: [{ required: true, message: '请填写登录账户', trigger: 'blur' }],
        userName: [{ required: true, message: '请填写昵称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur,change' },
          { pattern: /^1[12345789]\d{9}$/, message: '请输入正确的电话' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        userStatus: [{ required: true, message: '请账户状态', trigger: 'blur' }],
        roleList: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.queryTableData()
  },
  methods: {
    handleSizeChange(val) {
      this.page.pageSize = val
      this.queryTableData()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.queryTableData()
    },
    queryTableData() {
      this.fullscreenLoading = true
      var query = { 'page': this.page.currentPage, 'limit': this.page.pageSize }
      var qq = Object.assign(query, this.formInline)
      getUserList(qq).then(response => {
        this.tableData = response.data.list
        this.page = response.data.page
      })
      setTimeout(() => {
        this.fullscreenLoading = false
      }, 1000)
    },
    onAddUser(formName) {
      this.dialogTitle = '新增用户'
      this.dialogFormVisible = true
      this.editUserFormInline.roleList = []
      this.editUserFormInline.userId = ''
      this.editUserFormInline.userName = ''
      this.editUserFormInline.phone = ''
      this.editUserFormInline.sex = ''
      this.editUserFormInline.userStatus = ''
      this.editUserFormInline.loginName = ''
      this.transferData = []
      this.isAdd = true
      queryAuthRoleAllByStatus({ 'page': 1, 'limit': 99999 }).then(response => {
        const allRoles = response.data
        if (allRoles != null) {
          allRoles.forEach((p) => {
            this.transferData.push({
              key: p.id,
              label: p.name
            })
          })
        }
      })
    },
    onSubmit() {
      this.queryTableData()
      this.$notify({
        title: '查询成功',
        duration: 1000,
        type: 'success'
      })
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
    },
    queryUserInfo(val, fromName) {
      this.dialogTitle = '编辑用户信息'
      this.editUserFormInline.roleList = []
      this.transferData = []
      getUserByUserId({ 'userId': val + '' }).then(response => {
        const user = response.data.user
        const userRole = response.data.allRoles
        const roles = response.data.roles
        this.editUserFormInline.userId = user.id
        this.editUserFormInline.userName = user.userName
        this.editUserFormInline.phone = user.phone
        this.editUserFormInline.sex = user.sex
        this.editUserFormInline.userStatus = user.userStatus
        this.editUserFormInline.loginName = user.loginName
        if (userRole != null) {
          userRole.forEach((p) => {
            this.transferData.push({
              key: p.id,
              label: p.name
            })
          })
        }
        if (roles != null) {
          roles.forEach((p) => {
            this.transferData.forEach((item) => {
              if (p === item.key) {
                this.editUserFormInline.roleList.push(
                  item.key
                  // label: item.label
                )
              }
            })
          })
        }
      })

      this.dialogFormVisible = true
      this.isAdd = false
    },
    handleChange(value, direction, movedKeys) {
      // alert(value)
    },
    cancelChange(formName) {
      this.editUserFormInline.roleList = []
      this.transferData = []
      this.dialogFormVisible = false
      this.$refs[formName].clearValidate()
    },
    updateUserInfo(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          if (!this.isAdd) {
            updateAuthUserInfoAndRole(this.editUserFormInline).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.editUserFormInline.roleList = []
              this.transferData = []
              this.dialogFormVisible = false
              this.queryTableData()
            })
          } else {
            admin_register(this.editUserFormInline).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.editUserFormInline = []
              this.editUserFormInline.roleList = []
              this.transferData = []
              this.dialogFormVisible = false
              this.queryTableData()
            })
          }
        } else {
          return false
        }
      })
    },
    forbiddenUser(row, formName) {
      this.$confirm('确认要禁用该用户: ' + row.loginName + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateAuthUserInfoAndRole({ userId: row.id, userStatus: 2 }).then(response => {
          this.queryTableData()
          this.$notify({ title: response.msg, duration: 1000, type: 'success' })
        })
      }).catch(() => {
      })
    },
    resetUserPwd(row, formName) {
      this.$confirm('确认要重置该用户: ' + row.loginName + ' 的密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetUserPwd({ userId: row.id }).then(response => {
          this.$notify({ title: response.msg, duration: 1000, type: 'success' })
        })
      }).catch(() => {
      })
    },
    closeDialog(done) {
      done()
      if (this.isAdd) {
        location.reload()
      }
    },
    // 时间格式化
    dateFormat(row, column, cellValue, index) {
      const daterc = row[column.property]
      if (daterc != null) {
        const dateMat = new Date(parseInt(daterc.replace('/Date(', '').replace(')/', ''), 10))
        const year = dateMat.getFullYear()
        const month = dateMat.getMonth() + 1
        const day = dateMat.getDate()
        const hh = dateMat.getHours()
        const mm = dateMat.getMinutes()
        const ss = dateMat.getSeconds()
        const timeFormat = year + '/' + month + '/' + day + ' ' + hh + ':' + mm + ':' + ss
        return timeFormat
      }
    }
  }
}
</script>

<style scoped>
  ::v-deep .el-table th,
  ::v-deep .el-table td {
  text-align: center !important
  }
</style>
